<?php
namespace App\Http\Services;

class TencentCloudService
{
    public $secretId = 'AKIDlJp68xJye7SHsDLBoVyH1Wmp2ye6YffQ';
    public $secretKey = 'h9ML7f5Ggqrb5NSN4nHYZUBfnhdJkwsf';

    //查询某个直播状态
    public function IdCardVerification($xm='',$idcard=''){

        $data = [
            'IdCard' => $idcard,
            'Name'=>$xm
        ];

        //生成签名并调用接口
        $request = $this->requestWithResult( 'IdCardVerification' , '' , 'POST' , $data );
        $request = json_decode($request,true);
        return $request['Response'];

    }

    /***
     * 生成签名并调用接口
     * @param string $action 请求的方法名称
     * @param string $region 地域参数
     * @param string $method 请求方式
     * @param string $payLoad 请求携带的参数
     * @return Json 返回调用结果
     */
    public function requestWithResult( $action='' , $region = '' , $method = 'POST' , $payLoad = [] ){
        //请求时间
        $time = time();
        //签名参数
        $data = [
            'time' => $time,
            'credentialScope' => gmdate("Y-m-d", $time)."/faceid/tc3_request",
            'host' => "faceid.tencentcloudapi.com",
            '$secretKey' => $this->secretKey,
        ];

        //请求参数
        $params = [
            'HTTPRequestMethod' => $method,//HTTP 请求方式
            'CanonicalURI' => "/",//URI 参数，API 3.0 固定为正斜杠（/）
            'CanonicalQueryString' => $method == 'GET' ? http_build_query( $payLoad ) : '',
            'CanonicalHeaders' => "content-type:application/json\nhost:" . $data['host'] . "\n",//参与签名的头部信息,至少包含 host 和 content-type 两个头部
            'SignedHeaders' => 'content-type;host',//参与签名的头部信息，说明此次请求有哪些头部参与了签名
            'HashedRequestPayload' => hash( 'SHA256' , $this->ArrToJson($payLoad) ),//请求正文
        ];

        //公共头部参数
        $headers = [
            'Content-Type:application/json',
            'X-TC-Action:' . $action,
            'X-TC-Timestamp:' . $data['time'],
            'X-TC-Version:2018-03-01',
            'X-TC-Language: zh-CN',
            'Host:'.$data['host']
        ];

        if( !empty($region) ){
            $headers[] = 'X-TC-Region:' . $region;
        }

        //拼接请求串
        $canonicalRequest = join( "\n" , array_values( $params ) );

        //拼接待签名字符串
        $stringToSign = "TC3-HMAC-SHA256\n" .
            $data['time']. "\n" .
            $data['credentialScope']. "\n" .
            hash( 'SHA256' , $canonicalRequest );
//        print_r( $canonicalRequest );die;
        //计算签名
        $secretDate = hash_hmac("SHA256", gmdate("Y-m-d", $data['time']), "TC3".$this->secretKey, true);
        $secretService = hash_hmac("SHA256", "faceid", $secretDate, true);
        $secretSigning = hash_hmac("SHA256", "tc3_request", $secretService, true);
        $signature = hash_hmac("SHA256", $stringToSign, $secretSigning);

        $headers[] = 'Authorization:TC3-HMAC-SHA256 Credential=' . $this->secretId . '/' . $data['credentialScope'] . ', SignedHeaders=content-type;host, Signature=' . $signature;

        return $this->curlPost( 'https://' . $data['host'] , $payLoad , $headers );
    }

    private function curlPost($url = '',$post_data= '',$header_data=[]) {
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $ch = curl_init();//初始化curl

        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data, JSON_UNESCAPED_UNICODE));
        if(!empty($header_data)){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data);
        }

        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }

    private function curlGet($url = '',$post_data = [], $header_data = []){
        if (empty($url)) {
            return false;
        }
        if(count($post_data)>0){
            $o = "";
            foreach ( $post_data as $k => $v )
            {
                $o.= "$k=" . urlencode( $v ). "&" ;
            }
            $post_data = substr($o,0,-1);

            $url = $url.'?'.$post_data;
        }

        if(function_exists('curl_init')){
            $ch = curl_init();//初始化curl
            curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
            empty($header_data) && curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
            if(!empty($header_data)){
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data);
            }
            if(!empty($cookies)) {
                curl_setopt($ch, CURLOPT_COOKIE, $cookies);
            }
            $data = curl_exec($ch);//运行curl
            curl_close($ch);
        }else{
            $data = file_get_contents($url);
        }
        return $data;
    }

    //数组转json
    private function ArrToJson( $arr = [] ){
        if( empty($arr) ){
            return "{}";
        }

        return json_encode( $arr , 256 );
    }

}
